package com.banshuibao.bsb_android.adapter;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.model.ExpertRecorderDetailModel;
import com.banshuibao.bsb_android.util.MediaPlayerUtil;
import com.banshuibao.bsb_android.util.ParamsUtil;
import com.banshuibao.bsb_android.util.QuickDoubleClickable;
import com.banshuibao.bsb_android.util.TimeUtil;
import com.cunoraz.gifview.library.GifView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangpan on 2018/1/3.
 */

public class ListenRecordAdapter extends RecyclerView.Adapter<ListenRecordAdapter.ViewHolder> implements MediaPlayerUtil.MediaPlayerPlayingListener {

    private Context context;
    private List<ExpertRecorderDetailModel.DataBean.ExpertVoicesBean> list;
    private MediaPlayerUtil mediaPlayerUtil;
    private MediaPlayer media;
    private String time;
    private PopupWindow popupWindow;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        TextView textView;
        ViewHolder holder;
        private boolean stop = false;

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (!stop) {
                        sendEmptyMessageDelayed(0, 1000);
                        textView.setText(ParamsUtil.millsecondsToStr(media.getDuration() - media.getCurrentPosition()));
                        holder.relativeLayout.setEnabled(false);
                        holder.gifView.setVisibility(View.VISIBLE);
                        holder.show_iv.setVisibility(View.GONE);

                    }
                    break;
                case 1:
                    holder = (ViewHolder) msg.obj;
                    textView = holder.text_tv;
                    stop = false;
                    holder.relativeLayout.setEnabled(false);
                    break;
                case 2:
                    stop = true;
                    holder.gifView.setVisibility(View.GONE);
                    holder.show_iv.setVisibility(View.VISIBLE);
                    holder.relativeLayout.setEnabled(true);
                    holder.relativeLayout.setBackground(context.getResources().getDrawable(R.drawable.listenback));
                    textView.setText(time);
                    media.pause();
                    media.stop();
                    media.reset();
                    break;
            }
        }
    };

    public ListenRecordAdapter(final Context context) {
        this.context = context;
        list = new ArrayList<>();
        mediaPlayerUtil = new MediaPlayerUtil(context);
        mediaPlayerUtil.setOnMediaPlayerPlayingListener(this);
    }

    public void setData(List<ExpertRecorderDetailModel.DataBean.ExpertVoicesBean> expertVoices) {
        if (this.list != null) {
            this.list.clear();
            this.list.addAll(expertVoices);
            notifyDataSetChanged();
        }
    }
    @Override
    public ListenRecordAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.recorder_list_layout, null);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ListenRecordAdapter.ViewHolder holder, final int position) {
        final ExpertRecorderDetailModel.DataBean.ExpertVoicesBean expertVoicesBean = list.get(position);
        if (expertVoicesBean != null) {
            String uuid = expertVoicesBean.getUuid();
            final long voiceTime = expertVoicesBean.getVoiceTime();
            final String during = TimeUtil.formatDuring(voiceTime);
            holder.text_tv.setText(during);
            holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (QuickDoubleClickable.isDoubleClick()) {
                        return;
                    }
                    holder.relativeLayout.setBackground(context.getResources().getDrawable(R.drawable.listen_foucu));
                    if (media != null && media.isPlaying()) {
                        media.seekTo(0);
                        handler.sendEmptyMessage(2);
                        holder.relativeLayout.setEnabled(true);
                        holder.gifView.setVisibility(View.GONE);
                        holder.show_iv.setVisibility(View.VISIBLE);
                        holder.relativeLayout.setBackground(context.getResources().getDrawable(R.drawable.listenback));
                    } else {
                        time = String.valueOf(during);
                        Message msg = Message.obtain();
                        msg.what = 1;
                        msg.obj = holder;
                        handler.sendMessage(msg);
                        playAudio(expertVoicesBean.getName());
                    }
                }
            });
            holder.show_tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    showText(expertVoicesBean.getContent());
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return list != null ? list.size() : 0;
    }

    @Override
    public void OnError(MediaPlayer mediaPlayer) {

    }

    @Override
    public void OnPrepared(MediaPlayer mediaPlayer) {
        //开始播放
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            handler.sendEmptyMessageDelayed(0, 1000);
        }

    }

    @Override
    public void OnCompletion(MediaPlayer mediaPlayer) {
        handler.sendEmptyMessage(2);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout relativeLayout;
        TextView text_tv;
        ImageView show_iv;
        TextView show_tv;
        GifView gifView;
        public ViewHolder(View itemView) {
            super(itemView);
            relativeLayout = itemView.findViewById(R.id.play);
            text_tv = itemView.findViewById(R.id.text_tv);
            show_iv = itemView.findViewById(R.id.voice_iv);
            gifView = itemView.findViewById(R.id.voice_gif);
            show_tv = itemView.findViewById(R.id.show_tv);
            gifView.setGifResource(R.raw.play);
        }
    }

    /**
     * 播放语音
     */
    private void playAudio(String name) {
        media = mediaPlayerUtil.getNetMedia(Constants.Url.AUDIO_PLAY + name);
    }

    public void clear() {
        if (list != null) {
            list.clear();
            list = null;
        }
        media = null;
        if (mediaPlayerUtil != null) {
            mediaPlayerUtil.clearMediaPlayer();
        }
        if (handler != null) {
            handler.sendEmptyMessage(2);
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    /**
     * 查看文字
     */
    public void showText(String content){
        AlertDialog.Builder builder = new AlertDialog.Builder(context).setCancelable(false);  //先得到构造器
       // builder.setTitle("提示"); //设置标题
        builder.setMessage(content); //设置内容
//        builder.setPositiveButton("发布", new DialogInterface.OnClickListener() { //设置确定按钮
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//            }
//        });
        builder.setNegativeButton("已阅", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }
}

